package com.woniu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.domain.Goods;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.config.AlipayConfiguration;
import com.woniu.exception.userexp.YogaException;
import com.woniu.model.PagePayParam;
import com.woniu.model.Result;
import com.woniu.order.Form.AddLeagueClassDetailForm;
import com.woniu.order.Form.AddMemberCardOrderForm;
import com.woniu.order.Param.OrderPayParam;
import com.woniu.order.client.GoodsDto;
import com.woniu.order.client.ProductClient;
import com.woniu.order.client.model.MemberCard;
import com.woniu.order.dto.LeagueClassDetailDto;
import com.woniu.order.model.*;
import com.woniu.order.dao.MemberCardOrderDao;
import com.woniu.order.service.MemberCardOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.AlipayUtil;
import com.woniu.util.StateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@Service

public class MemberCardOrderServiceImpl extends ServiceImpl<MemberCardOrderDao, MemberCardOrder> implements MemberCardOrderService {

    @Resource
    private ProductClient productClient;

    @Resource
    private AlipayUtil alipayUtil;
    @Resource
    private MemberCardOrderDao memberCardOrderDao;
    @Resource
    private AlipayConfiguration alipayConfiguration;


    @Override
    public void finishLeagueClassDetail(Integer leagueClassWorkforceId) {

    }

    @Override
    public void cancelLeagueClassDetail(Integer leagueClassWorkforceId) {
        List<LeagueWorkforce> leagueClassDetails = baseMapper.selectList(new QueryWrapper<LeagueWorkforce>().eq("league_class_workforce_id", leagueClassWorkforceId));
        for (LeagueWorkforce l : leagueClassDetails) {
            l.setLeagueClassWorkforceState(StateUtil.LEAGUE_CLASS_STATE_START);//完成
            baseMapper.updateById(l);
        }
    }

    @Override
    public List<LeagueClassDetailDto> loadLeagueClassDetailByUser(Integer userId, Integer classState, String leagueClassName) {
        QueryWrapper<LeagueWorkforce> wrapper = new QueryWrapper();
        if (classState != null) {
            wrapper.eq("league_class_state", classState);
        }
        if (leagueClassName != null) {

            List<LeagueClass> list = productClient.loadLeagueClassByName(leagueClassName).getData();

            Set<Integer> collect = list.stream().map(o -> o.getLeagueClassId()).collect(Collectors.toSet());
            wrapper.in("league_class_id", collect);
        }
        wrapper.eq("user_id", userId);
        List<LeagueWorkforce> details = baseMapper.selectList(wrapper);
        ArrayList<LeagueClassDetailDto> dtos = new ArrayList<>();
        for (LeagueWorkforce d : details) {
            LeagueClassDetailDto dto = new LeagueClassDetailDto();
            dto.setDetail(dto.getDetail());
            dto.setLeagueClass(BeanUtil.toBean(productClient.ByIdLeagueClass(d.getLeagueClassId()).getData(), LeagueClass.class));
            dtos.add(dto);
        }
        return null;
    }

    @Override
    public void addLeagueClassDetail(AddLeagueClassDetailForm form) {
        List<YUserLeagueClassMargin> margins = form.getMargins();

        for (YUserLeagueClassMargin margin : margins) {
            Integer userLeagueClassMarginId = margin.getId();

            MemberCardOrder memberCardOrder = new MemberCardOrder();
            //memberCardOrder.setOrderNum();
            memberCardOrder.setUserId(margin.getUserId());
            memberCardOrder.setVenueId(null);
            memberCardOrder.setCarId(null);
            memberCardOrder.setUserCardId(null);
            //memberCardOrder.setOrderMoney() ;
            memberCardOrder.setFinishTime(form.getEndTime());
            memberCardOrder.setOrderState(StateUtil.LEAGUE_CLASS_STATE_FULL);
            memberCardOrder.setOrderPaytime(null);


            YLeagueClassDetail detail = new YLeagueClassDetail();
            detail.setStartTime(form.getStartTime());
            detail.setEndTime(form.getEndTime());
            detail.setCoachId(form.getCoachId());
            detail.setUserId(margin.getUserId());
            detail.setUserLeagueClassMarginId(userLeagueClassMarginId);
            detail.setLeagueClassState(StateUtil.LEAGUE_CLASS_STATE_FULL);//未完成
            detail.setLeagueClassId(form.getLeagueClassId());
            detail.setLeagueClassWorkforceId(form.getLeagueClassWorkforceId());
            baseMapper.insert(detail);
        }
    }

    /**
     * 新增会员卡订单
     *
     * @param form
     * @return
     */
    @Override
    public void addMemberCardOrder(AddMemberCardOrderForm form) throws Exception {
        Result<MemberCard> memberCardResult = productClient.getCardById(form.getCardId());
        if (BeanUtil.isNotEmpty(memberCardResult.getData())) {
            MemberCard memberCardEntity = memberCardResult.getData();
            MemberCardOrder memberCardOrder = new MemberCardOrder();
            memberCardOrder.setUserId(form.getUserId() );
            memberCardOrder.setOrderNum(UUID.randomUUID().toString());

            memberCardOrder.setVenueId(null);
            memberCardOrder.setCarId(form.getCardId());
            //memberCardOrder.setUserCardId( null ) ;
            memberCardOrder.setOrderMoney(memberCardEntity.getCardPrice().multiply(new BigDecimal(form.getCardNumber())));
            memberCardOrder.setFoundDate(LocalDateTime.now());
            memberCardOrder.setOrderState(StateUtil.ORDER_STATE_NOT_PAY);
            //memberCardOrder.setFinishTime(form.getEndTime() );
            //memberCardOrder.setOrderPaytime(null ) ;
            baseMapper.insert(memberCardOrder);
        } else {
            throw new YogaException( 500,"请选择正确的会员卡类型");
        }
    }
    @Override
    public Object pay(OrderPayParam orderPayParam) throws Exception {
        //1.检验传进来的参数是否正确
        QueryWrapper<MemberCardOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",orderPayParam.getOrderNum());
        MemberCardOrder memberCardOrder = memberCardOrderDao.selectOne(wrapper);
        if (memberCardOrder == null ||!Objects.equals(memberCardOrder.getOrderNum(), orderPayParam.getOrderNum())){
            throw new YogaException(500,"订单不存在");
        }
        if (!Objects.equals(memberCardOrder.getOrderState(), StateUtil.GOODS_ORDER_STATE_DISABLED)){
            throw new YogaException(500,"订单状态异常");
        }
        //2.组装参数
        PagePayParam payParam = new PagePayParam(); // 使用正确包下的 PagePayParam
        payParam.setBody("会员卡订单支付");
        payParam.setMoney(memberCardOrder.getOrderMoney().doubleValue());
        payParam.setNotifyUrl("http://localhost:8081/order/goodsOrder/notify");
        payParam.setReturnUrl("http://localhost:8081/order/goodsOrder/notify");
        payParam.setOrderId(memberCardOrder.getOrderNum());
        payParam.setSubject("yoga");
        //取出数据库订单的下单时间
        LocalDateTime payTime = memberCardOrder.getFoundDate() ;

        LocalDateTime expireLocalDateTime = payTime.plusMinutes(60);
        long expireTime = Date.from(expireLocalDateTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();
        long now = new Date().getTime();
        int minute = (int)((expireTime - now)/1000/60);
        if (minute < 1 ){
            throw new YogaException(500,"订单超时");
        }
        Date date = new Date(expireTime);
        String expire = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        payParam.setTimeExpire(expire);//可支付的时间
        //调用支付宝工具类
        return alipayUtil.pagePay(payParam);
    }
    @Override
    public void payNotify(Map<String, String> map) throws Exception {
        //第一步验签
        boolean signVerified = AlipaySignature.rsaCheckV1(map, alipayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
        if (signVerified) {
            //验签成功


            String status = map.get("trade_status");

            if ("TRADE_SUCCESS".equals(status)){
                String orderNum = map.get("out_trade_no");
                //支付成功
                //修改订单状态为支付
                QueryWrapper<MemberCardOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_num",orderNum);
                MemberCardOrder memberCardOrder = memberCardOrderDao.selectOne(queryWrapper);

                if (Objects.equals(memberCardOrder.getOrderState(), StateUtil.GOODS_ORDER_STATE_DISABLED)) {
                    //如果订单状态是未支付才进下一步操作
                    memberCardOrder.setOrderState(StateUtil.GOODS_ORDER_STATE_START);
                    String payTimeStr = map.get("send_pay_date");
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime parse = LocalDateTime.parse(payTimeStr, formatter);
                    memberCardOrder.setOrderPaytime(LocalDateTime.parse(String.valueOf(parse)));
                    //修改冻结量
                    List<MemberCardOrder> list = memberCardOrderDao.selectList(new QueryWrapper<MemberCardOrder>().eq("order_num", orderNum));
                    for (MemberCardOrder item :list){
                        Result<GoodsDto> GoodsDtoResult = productClient.byId(item.getUserCardId());
                        GoodsDto data = GoodsDtoResult.getData();
                        Goods goods = BeanUtil.toBean(data, Goods.class);
                        productClient.updateByIdGoods(goods);
                    }
                    MemberCardOrder MemberCardOrder = new MemberCardOrder();
                    memberCardOrderDao.updateById(MemberCardOrder);
                }
            }
        }
    }

    @Override
    public void membershipcardcancellation(Integer menberuserid) {
        List<MemberCardOrder> leagueClassDetails = baseMapper.selectList(new QueryWrapper<MemberCardOrder>().eq("user_id", menberuserid));
        for (MemberCardOrder l : leagueClassDetails) {
            l.setOrderState(StateUtil.GOODS_ORDER_STATE_FULL);//完成
            baseMapper.updateById(l);
        }
    }



}
